module StjzbServer
  class Stjzb
    attr_accessor :players, :round

    SHI_TOU = 1
    JIAN_ZI = 2
    BU = 3

    # 5局3胜
    def initialize(player1, player2)
      player1.current_win_rounds = 0
      player2.current_win_rounds = 0
      player1.current_action = nil
      player2.current_action = nil
      @players = [ player1, player2 ]
      @round = 1
      @target = 3

      player1.current_battle = player2.current_battle = self
      player1.current_opponent, player2.current_opponent = player2, player1
      player1.battling!
      player2.battling!

      instruction = "#{@target * 2 - 1}局#{@target}胜"
      player2.send_message_matched(instruction)
      player1.send_message_matched(instruction)
      puts "#{player1.loginname} vs #{player2.loginname}, #{@target}/#{@target * 2 - 1}"
    end

    def act(player, action)
      player.current_action = action.to_i
      if player.current_opponent.current_action
        act1, act2 = player.current_action, player.current_opponent.current_action
        case act1 <=> act2
        when -1
          act1 - act2 == -1 ? bigger(player, player.current_opponent) : bigger(player.current_opponent, player)
        when 0
          draw(player, player.current_opponent)
        when 1
          act1 - act2 == 2 ? bigger(player, player.current_opponent) : bigger(player.current_opponent, player)  
        end

        player.current_action = player.current_opponent.current_action = nil
        @round += 1
      end
    end

    private

    def draw(player1, player2)
      player1.send_message_round_finished(@round, '=')
      player2.send_message_round_finished(@round, '=')
    end

    def bigger(player1, player2)
      player1.current_win_rounds += 1
      player1.send_message_round_finished(@round, '>')
      player2.send_message_round_finished(@round, '<')
      if player1.current_win_rounds >= @target
        player1.win
      end
    end

  end
end
